/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.client.impl.consumer;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.common.ServiceThread;
import org.apache.rocketmq.common.utils.ThreadUtils;
import org.slf4j.Logger;

public class PullMessageService extends ServiceThread {
    private final Logger log = ClientLogger.getLog();
    private final LinkedBlockingQueue<PullRequest> pullRequestQueue = new LinkedBlockingQueue<PullRequest>();
    private final MQClientInstance mQClientFactory;
    private final ScheduledExecutorService scheduledExecutorService = Executors
        .newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "PullMessageServiceScheduledThread");
            }
        });

    public PullMessageService(MQClientInstance mQClientFactory) {
        this.mQClientFactory = mQClientFactory;
    }

    /**
     * 延迟 timeDelay(ms)的时间 投递消息到pullRequestQueue
      */
    public void executePullRequestLater(final PullRequest pullRequest, final long timeDelay) {
        this.scheduledExecutorService.schedule(new Runnable() {

            @Override
            public void run() {
                PullMessageService.this.executePullRequestImmediately(pullRequest);
            }
        }, timeDelay, TimeUnit.MILLISECONDS);
    }

    /**
     *  立即投递消息到pullRequestQueue
     */
    public void executePullRequestImmediately(final PullRequest pullRequest) {
        try {
            this.pullRequestQueue.put(pullRequest);
        } catch (InterruptedException e) {
            log.error("executePullRequestImmediately pullRequestQueue.put", e);
        }
    }

    public void executeTaskLater(final Runnable r, final long timeDelay) {
        this.scheduledExecutorService.schedule(r, timeDelay, TimeUnit.MILLISECONDS);
    }

    public ScheduledExecutorService getScheduledExecutorService() {
        return scheduledExecutorService;
    }

    /**
     * 拉取消息的具体逻辑，前提是必须拿到pullRequest
     */
    private void pullMessage(final PullRequest pullRequest) {
        // 从当前MQClientInstance的consumerTable中根据consumerGroup选取consumer实例,
        // 同一个MQClientInstance下同一个consumerGroup，只会对应一个consumer实例，语雀笔记有写
        final MQConsumerInner consumer = this.mQClientFactory.selectConsumer(pullRequest.getConsumerGroup());
        if (consumer != null) {
            // 这里只针对 pushConsumer 推模式，因为拉模式pull是消费方主动调取拉取消息API拉取消息的，不需要通过pullMessageService的定时任务拉取
            // 这里将consumer强转为DefaultMQPushConsumerImpl
            DefaultMQPushConsumerImpl impl = (DefaultMQPushConsumerImpl) consumer;
            // 通过pullRequest拉取消息
            impl.pullMessage(pullRequest);
        } else {
            log.warn("No matched consumer for the PullRequest {}, drop it", pullRequest);
        }
    }

    /**
     * 此任务是在单个MQClientInstance下执行的，也就是如果对应不同的消费者consumer实例，每个consumer实例在启动的时候都会启动该任务
     *
     * 一个pullRequest代表一次拉取请求的执行，首次拉取请求是通过rebalance机制进行重新负载发起的，并且如果消费者的重新负载消息队列发生改变，
     * rebalance会创建新的pullRequest到pullRequestQueue中，并且会定时移除不必要的MessageQueue或ProcessQueue，之后就是pullMessage方法
     * 中根据消息拉取情况不断的触发新的拉取请求pullRequest，不断从broker拉取消息，而不是每次都是rebalance创建pullRequest拉取消息了，这点要清楚
     *
     */
    @Override
    public void run() {
        log.info(this.getServiceName() + " service started");
        // 死循环，不停的从pullRequestQueue队列中拉取PullRequest。stopped是volatile，其它线程可以控制stopped开关进而停止此循环
        while (!this.isStopped()) {
            try {
                // pullRequestQueue 是 LinkedBlockingQueue ，调用take()从队列中拉取PullRequest，如果队列无内容，当前线程阻塞
                PullRequest pullRequest = this.pullRequestQueue.take();
                if (pullRequest != null) {
                    // 核心拉取方法
                    this.pullMessage(pullRequest);
                }
            } catch (InterruptedException e) {
            } catch (Exception e) {
                log.error("Pull Message Service Run Method exception", e);
            }
        }

        log.info(this.getServiceName() + " service end");
    }

    @Override
    public void shutdown(boolean interrupt) {
        super.shutdown(interrupt);
        ThreadUtils.shutdownGracefully(this.scheduledExecutorService, 1000, TimeUnit.MILLISECONDS);
    }

    @Override
    public String getServiceName() {
        return PullMessageService.class.getSimpleName();
    }

}
